//
//  SignatureVC.m
//  Collection
//
//  Created by Home on 9/15/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//


#define SCROLLVIEW_CONTENT_HEIGHT 460
#define SCROLLVIEW_CONTENT_WIDTH  320


#import "SignatureVC.h"
#import "VehicleController.h"
#import "CustomerSignatureController.h"
#import "PreviewController.h"

CGFloat animatedDistance;
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 210;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;
//anyView has been defined for different kind of views to avoid keyboard when entering data in textfield.
UIView *anyView;

@implementation SignatureVC
@synthesize selector,sender;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(IBAction)returnMe;
{
	[sender performSelector:selector];
	[self buttonNextAction];
	 

}

- (void)dealloc
{
    [vehicleTypeArr_ release];
    [vehicleTypeDropDownView release];
    
    [VATVehicleTypeArr_ release];
    [VATVehicleTypeDropDownView release];
    
    [carSectionArr_ release];
    [carSectionDropDownView release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    cache = [NSUserDefaults standardUserDefaults];
    
    self.navigationItem.title = @" Other Details";
    
    UIBarButtonItem *settingNavigationItem = [[UIBarButtonItem alloc]initWithTitle:@"Next" style:UIBarButtonItemStyleBordered target:self action:@selector(buttonNextAction)];
    settingNavigationItem.style = UIBarButtonItemStyleBordered;
    [self.navigationItem setRightBarButtonItem:settingNavigationItem];
    [settingNavigationItem release];
    
    
    vehicleTypeArr_ = [[NSArray alloc] initWithArray:[NSArray arrayWithObjects:@"Standard Vehicle",@"Large Vehicle",nil]]; 
    [vehicleTypeBtn_ setTitle:[vehicleTypeArr_ objectAtIndex:0] forState:UIControlStateNormal];
    vehicleTypeDropDownView = [[DropDownView alloc] initWithArrayData:vehicleTypeArr_ cellHeight:20 heightTableView:60 paddingTop:0 paddingLeft:-5 paddingRight:-10 refView:vehicleTypeBtn_ animation:BLENDIN openAnimationDuration:2 closeAnimationDuration:2];
	
	vehicleTypeDropDownView.delegate = self;
	
	[self.view addSubview:vehicleTypeDropDownView.view];
    
    
    VATVehicleTypeArr_ = [[NSArray alloc] initWithArray:[NSArray arrayWithObjects:@"Full Valet 58.0",@"Exterior Valet Only 35.0",@"Interior Valet Only 44.0",nil]];
    [vehicleTypeVATBtn_ setTitle:[VATVehicleTypeArr_ objectAtIndex:0] forState:UIControlStateNormal];
    VATVehicleTypeDropDownView = [[DropDownView alloc] initWithArrayData:VATVehicleTypeArr_ cellHeight:20 heightTableView:60 paddingTop:0 paddingLeft:-5 paddingRight:-10 refView:vehicleTypeVATBtn_ animation:BLENDIN openAnimationDuration:2 closeAnimationDuration:2];
	
	VATVehicleTypeDropDownView.delegate = self;
	
	[self.view addSubview:VATVehicleTypeDropDownView.view];
    
    carSectionArr_ = [[NSArray alloc] initWithArray:[NSArray arrayWithObjects:@"Car Section1",@"Car Section2",@"Car Section3",@"Car Section4",nil]];
   // [vehicleTypeVATBtn_ setTitle:[VATVehicleTypeArr_ objectAtIndex:0] forState:UIControlStateNormal];
    carSectionDropDownView = [[DropDownView alloc] initWithArrayData:carSectionArr_ cellHeight:20 heightTableView:refView_.frame.size.height paddingTop:0 paddingLeft:-5 paddingRight:-10 refView:refView_ animation:BLENDIN openAnimationDuration:2 closeAnimationDuration:2];
	
	carSectionDropDownView.delegate = self;
	
	[objScrollView_ addSubview:carSectionDropDownView.view];


    objScrollView_.contentSize = CGSizeMake(320, 650);
    itemsScrollView_.contentSize = CGSizeMake(350, 850);
    
    
    drawImage = [[UIImageView alloc] initWithImage:nil];
    drawImage.frame = CGRectMake(0, 0, customerSignatureView_.frame.size.width, customerSignatureView_.frame.size.height);
    [customerSignatureView_ addSubview:drawImage];
    
    
    driverDrawImage = [[UIImageView alloc] initWithImage:nil];
    driverDrawImage.frame = CGRectMake(0, 0, driverSignatureView_.frame.size.width, driverSignatureView_.frame.size.height);
    [customerSignatureView_ addSubview:driverDrawImage];
//    self.view.backgroundColor = [UIColor lightGrayColor];
    mouseMoved = 0;
    [self.view bringSubviewToFront:btnSave];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    
   // toolbar.hidden = YES;   
    
    mouseSwiped = NO;
    UITouch *touch = [touches anyObject];
    
    if ([touch tapCount] == 2) {
        drawImage.image = nil;
        return;
    }
    
    lastPoint = [touch locationInView:self.view];
    lastPoint.y -= 20;
    
}


- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    mouseSwiped = YES;
    
    UITouch *touch = [touches anyObject];   
    CGPoint currentPoint = [touch locationInView:self.view];
    currentPoint.y -= 20;
    
    
    UIGraphicsBeginImageContext(self.view.frame
                                .size);
    [drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
    CGContextBeginPath(UIGraphicsGetCurrentContext());
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextStrokePath(UIGraphicsGetCurrentContext());
    drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    lastPoint = currentPoint;
    
    mouseMoved++;
    
    if (mouseMoved == 10) {
        mouseMoved = 0;
    }
    
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [touches anyObject];
    
    if ([touch tapCount] == 2) {
       // toolbar.hidden = NO;
        drawImage.image = nil;
        return;
    }
    
    
    if(!mouseSwiped) {
        UIGraphicsBeginImageContext(self.view.frame.size);
        [drawImage.image drawInRect:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
        CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
        CGContextSetLineWidth(UIGraphicsGetCurrentContext(), 5.0);
        CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), 1.0, 0.0, 0.0, 1.0);
        CGContextMoveToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), lastPoint.x, lastPoint.y);
        CGContextStrokePath(UIGraphicsGetCurrentContext());
        CGContextFlush(UIGraphicsGetCurrentContext());
        drawImage.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}
-(IBAction)buttonSaveImageAction:(id)sender;{
    NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"];
    NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.jpg"];
    
    // Write a UIImage to JPEG with minimum compression (best quality)
    // The value 'image' must be a UIImage object
    // The value '1.0' represents image compression quality as value from 0.0 to 1.0
    [UIImageJPEGRepresentation(drawImage.image, 1.0) writeToFile:jpgPath atomically:YES];
    
    // Write image to PNG
    [UIImagePNGRepresentation(drawImage.image) writeToFile:pngPath atomically:YES];
    
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)buttonNextAction
{
    [cache setValue:areaOfDemageTF_.text forKey:@"areaOfDemage"];
    [cache setValue:vehicleTypeBtn_.titleLabel.text forKey:@"vehicleType"];
    [cache setValue:vehicleTypeVATBtn_.titleLabel.text forKey:@"vechicleTypeWithVAT"];
    [cache setValue:additionalCommentTV_.text forKey:@"additionalComment"];
    [cache setValue:unableCheckTV_.text forKey:@"unableCheckVehicle"];
    
    
        
    
   PreviewController *objController = [[PreviewController alloc] init];
   [self.navigationController pushViewController:objController animated:YES];
   [objController release];

}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark -
#pragma mark textView Delegate

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    /*if([textView.text length] <= 0)
     {
     textView.text = @"About Me";
     }*/
    if ([text isEqualToString:@"\n"]) {
        
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}


- (void)textViewDidBeginEditing:(UITextView *)textView
{
	
		anyView = self.view;
	
	
	
	
 	CGRect textFieldRect = [anyView.window convertRect:textView.bounds fromView:textView];
 	CGRect viewRect =
 	[anyView.window convertRect:self.view.bounds fromView:self.view];
 	CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
 	CGFloat numerator =
 	midline - viewRect.origin.y
 	- MINIMUM_SCROLL_FRACTION * viewRect.size.height;
 	CGFloat denominator =
 	(MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
 	* viewRect.size.height;
 	CGFloat heightFraction = numerator / denominator;
 	if (heightFraction < 0.0)
 	{ 
		heightFraction = 0.0;
 	}
 	else if (heightFraction > 1.0)
 	{
		heightFraction = 1.0;
 	}
 	UIInterfaceOrientation orientation =
 	
	[[UIApplication sharedApplication] statusBarOrientation];
 	if (orientation == UIInterfaceOrientationPortrait ||
		orientation == UIInterfaceOrientationPortraitUpsideDown)
 	{
		animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
 	}
 	else
 	{
		animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
 	}
	
 	CGRect viewFrame = self.view.frame;
 	viewFrame.origin.y -= animatedDistance;
	
 	[UIView beginAnimations:nil context:NULL];
 	[UIView setAnimationBeginsFromCurrentState:YES];
 	[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
 	[anyView setFrame:viewFrame];
 	[UIView commitAnimations];	
	
}


- (void)textViewDidEndEditing:(UITextView *)textView
{
	
	CGRect viewFrame = self.view.frame;
	viewFrame.origin.y += animatedDistance;
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationBeginsFromCurrentState:YES];
	[UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
	[anyView setFrame:viewFrame];
	[UIView commitAnimations];
}

#pragma mark -
#pragma mark DropDownViewDelegate

-(void)dropDownCellSelected:(NSInteger)returnIndex{
    if(selectedBtnTag > 0 && selectedBtnTag <=24)
    {
        [refButton setTitle:[carSectionArr_ objectAtIndex:returnIndex] forState:UIControlStateNormal];
    }
    else
    if(selectedBtnTag == 25)
    {
        [vehicleTypeBtn_ setTitle:[vehicleTypeArr_ objectAtIndex:returnIndex] forState:UIControlStateNormal];
        
    }
    else 
    {
        [vehicleTypeVATBtn_ setTitle:[VATVehicleTypeArr_ objectAtIndex:returnIndex] forState:UIControlStateNormal];
    }
}	
-(IBAction)actionButtonClick:(UIButton*)sender{
   
    selectedBtnTag = sender.tag;
    refButton = sender;
   
    if(sender.tag >0 && sender.tag <=24)
    {
        [carSectionDropDownView openAnimation];
    }
    else
    if(sender.tag == 25)
    {
        [vehicleTypeDropDownView openAnimation];
    }
    else
    {
        [VATVehicleTypeDropDownView openAnimation];
    }
    
}

@end
